package models

import (
	"log"

	"github.com/gofrs/uuid"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"gorm.io/plugin/soft_delete"
)

var db *gorm.DB
var err error

// Model base model
type Model struct {
	UUID uuid.UUID `gorm:"type:char(36);primaryKey" json:"uuid"`
	// CreatedAt time.Time      `json:"created_at"`
	// UpdatedAt time.Time      `json:"updated_at"`
	CreatedAt int                   `json:"created_at"`
	UpdatedAt int                   `json:"updated_at"`
	DeletedAt soft_delete.DeletedAt `gorm:"index" json:"deleted_at"`
}

// BeforeCreate 自动创建id
func (m *Model) BeforeCreate(tx *gorm.DB) (err error) {
	if m.UUID.String() == uuid.Nil.String() {
		m.UUID, err = uuid.NewV4()
	}
	return
}

func init() {
	dsn := "root:root@tcp(localhost:3306)/go_comm?charset=utf8mb4&parseTime=True&loc=Local" // go_comm 是数据库名称

	db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: logger.Default.LogMode(logger.Info), // 设置输出日志
	})
	if err != nil {
		log.Println("mysql err :", err)
	}

	err = db.AutoMigrate(&Account{}, &Message{}) // 建表
	if err != nil {
		log.Println("AutoMigrate err :", err)
	}
}
